<?php

namespace Manager;

use W3\Util;
use Base\Contents as Manager;

!defined('W3_ROOT_DIR') AND exit;

/**
 * 内容编辑管理基类
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */

class Contents extends Manager
{
    /**
     * 插入内容
     *
     * @access public
     * @param array $values 数组
     * @return integer
     */
    public function addContents( array $values )
    {
        /** 构建插入结构 */
        $content = [
			'mids'          =>  empty($values['mids']) ? '' : $values['mids'],
			'title'         =>  empty($values['title']) ? '' : htmlspecialchars($values['title']),
			'uid'           =>  isset($values['uid']) ? intval($values['uid']) : $this->auth->uid,
			/** 避免冲突 */
			'alias'         =>  Util::alias(),
            'type'          =>  empty($values['type']) ? 'post' : $values['type'],
            'status'        =>  empty($values['status']) ? 'publish' : $values['status'],
            'intro'         =>  empty($values['intro']) ? '' : $values['intro'],
			'pic'           =>  empty($values['pic']) ? '' : $values['pic'],
			'template'      =>  empty($values['template']) ? '' : $values['template'],
            'text'          =>  empty($values['text']) ? '' : $this->filterText($values['text']),
            'created'       =>  empty($values['created']) ? $this->config->time : $values['created'],
            'modified'      =>  $this->config->time,
            'commentsNum'   =>  empty($values['commentsNum']) ? 0 : intval($values['commentsNum']),
            'allowComment'  =>  !empty($values['allowComment']) && 1 == $values['allowComment'] ? 1 : 0,
			'tagsJson'      =>  empty($values['tagsJson']) ? '' : $values['tagsJson'],
            'imagesNum'     =>  empty($values['imagesNum']) ? 0 : intval($values['imagesNum']),
            'filesNum'      =>  empty($values['filesNum']) ? 0 : intval($values['filesNum']),
            'order'         =>  empty($values['order']) ? 0 : intval($values['order']),
        ];

        if (!empty($values['cid'])) {
            $content['cid'] = $values['cid'];
        }

        /** 首先插入部分数据 */
        $insertId = $this->db
		    ->insert('table.contents')
		    ->rows($content)
			->lastId();
			
		/** 更新缩略名 */
        if ($insertId > 0 ) 

			$this->applyAlias(empty($values['alias']) ? $insertId : $values['alias'], $insertId);
			
        return $insertId;
    }

    /**
     * 更新内容
     *
     * @access public
     * @param int $cid 内容cid
     * @param array $values 数组
     * @return integer
     */
    public function updateContents( $cid, array $values )
    {
        /** 构建插入结构 */
        $update = [
			'mids'          =>  empty($values['mids']) ? '' : $values['mids'],
			'title'         =>  empty($values['title']) ? '' : htmlspecialchars($values['title']),
			'uid'           =>  isset($values['uid']) ? intval($values['uid']) : $this->auth->uid,
            'type'          =>  empty($values['type']) ? 'post' : $values['type'],
            'status'        =>  empty($values['status']) ? 'publish' : $values['status'],
			'alias'         =>  empty($values['alias']) ? '' : $values['alias'],
            'intro'         =>  empty($values['intro']) ? '' : $values['intro'],
			'pic'           =>  empty($values['pic']) ? '' : $values['pic'],
			'template'      =>  empty($values['template']) ? '' : $values['template'],
            'text'          =>  empty($values['text']) ? '' : $this->filterText($values['text']),
            'commentsNum'   =>  empty($values['commentsNum']) ? 0 : intval($values['commentsNum']),
            'allowComment'  =>  !empty($values['allowComment']) && 1 == $values['allowComment'] ? 1 : 0,
			'tagsJson'      =>  empty($values['tagsJson']) ? '' : $values['tagsJson'],
            'imagesNum'     =>  empty($values['imagesNum']) ? 0 : intval($values['imagesNum']),
            'filesNum'      =>  empty($values['filesNum']) ? 0 : intval($values['filesNum']),
            'order'         =>  empty($values['order']) ? 0 : intval($values['order']),
        ];
		
        $content = [];
        foreach ($values as $key => $val) 
		{
            if (array_key_exists($key, $update)) {
                $content[$key] = $update[$key];
            }
        }

		/** 检测更新缩略名 */
        array_key_exists('alias', $values) 
		    && $meta['alias'] = $this->applyAlias(empty($values['alias']) ? $cid : $values['alias'], $cid);
		
        /** 更新创建时间 */
        if (!empty($values['created'])) {
            $content['created'] = $values['created'];
        }

        $content['modified'] = $this->config->time;
		
        $updateRows = $this->db
		    ->update('table.contents')
		    ->where('cid = ?', $cid)
		    ->rows($content)
		    ->affected();

        return $updateRows;
    }

    /**
     * 删除内容
     *
     * @access public
     * @param int $cid 内容cid
     * @return integer
     */
    public function deleteContents( $cid )
    {
        return $this->db
		    ->delete('table.contents')
		    ->where('cid = ?', $cid)
			->affected();
    }

    /**
     * filterText 
     * 
     * @param mixed $text 
     * @access public
     * @return string
     */
    public function filterText( $html )
    {
		/** 插件接口 */
		return \action_exists('contents_filter_text') 
		    ? \do_action('contents_filter_text', $this, false, $html)
			: Util::removeXss($html);
    }
	
    /**
     * 为内容应用缩略名
     *
     * @access public
     * @param string $alias 缩略名
     * @param mixed $cid 内容id
     * @return string
     */
    public function applyAlias( $alias, $cid )
    {
		/** 插件接口 */
        if (\action_exists('contents_alias')) {
            return \do_action('contents_alias', $this, false, $alias, $cid);
        }
		
		$count = 1;
		$org_alias = $alias;
		$pass = true;
		
        /** 判断是否在数据库中已经存在 */
        while (true) 
		{
			$row = $this->db
				->select('cid')
			    ->from('table.contents')
                ->where('alias = ?', $alias)
			    ->fetch();
				
			if($row){
				if($row['cid'] != $cid){
                    $alias = $count > 1  ? $org_alias . '-' . $count : $alias . '-' . $count;
                    $count ++;
			    } else {
					$pass = false;
					break;
				}
			} else {
				break;
			}
        }
		
		$pass && $this->db
		    ->update('table.contents')
		    ->where('cid = ?', $cid)
			->rows(['alias'=>$alias])
			->affected();
			
        return $alias;
    }
	
	/**
	 * 递增数值
	 *
	 * @access public
	 * @param int|string $cid 
	 * @param string     $field  
	 * @param int        $num 
	 * @return false|int 
	 */
	public function incr( $cid, $field, $num = 1 )
	{
		$num = max(1, (int) $num);
		
        /** 更新内容数 */
		return $this->db->update('table.contents')
		    ->where('table.contents.cid = ?', $cid)
		    ->expression($field, "$field + $num")
			->affected();
	}
	
	/**
	 * 递减数值
	 *
	 * @access public
	 * @param int|string $cid 
	 * @param string     $field  
	 * @param int        $num 
	 * @return false|int 
	 */
	public function decr( $cid, $field, $num = 1 )
	{
		$num = max(1, (int) $num);
		
        /** 更新内容数 */
		return $this->db->update('table.contents')
		    ->where("table.contents.cid = ? and $field >= ?", $cid, $num)
		    ->expression($field, "$field - $num")
			->affected();
	}
}

